import json
import re
from http.client import responses

from django.contrib.auth import get_user_model, login, logout, authenticate
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import DatabaseError
from django.http import JsonResponse, HttpResponseForbidden
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View

from apps.verifications.views import logger

User = get_user_model()

class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 获取表单数据，传统表单提交
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})

        # 登录用户，状态保持
        login(request, user)

        response = redirect(reverse('index:index'))
        # 设置cookie
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        return response

# 登录视图类
# 使用Django认证系统提供的登录功能
class LoginView(View):
    """用户登录"""

    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        # 获取表单数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 调用Django认证系统提供的登录功能
        user = authenticate(request, username=username, password=password)
        if user:
            # 登录成功，状态保持
            login(request, user)
            # 设置cookie
            response = redirect(reverse('index:index'))
            response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
            return response
        else:
            return render(request, 'login.html', {'login_errmsg': '用户名或密码错误'})


class LogoutView(View):
    """用户退出登录"""

    def get(self, request):
        # 清除状态保持信息
        logout(request)
        # 响应结果 重定向到首页
        response = redirect(reverse('index:index'))
        # 删除cookie中的用户名
        response.delete_cookie('username')
        return response

class UsernameCountView(View):
    """判断用户名是否重复注册"""
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'count': count})

class MobileCountView(View):
    """判断手机号是否重复注册"""
    def get(self, request, mobile):
        print(mobile)
        count = User.objects.filter(mobile=mobile).count()
        count = User.objects.filter(username=mobile).count()
        return JsonResponse({'count': count})

class UserInfoView(View):
    """用户中心"""

    def get(self, request):
        # 获取登录用户
        user = request.user
        # 判断用户是否登录
        if user.is_authenticated:
            context = {
                'username': user.username,
                'mobile': user.mobile,
                'email': user.email,
            }
            return render(request, 'user_center_info.html', context=context)
        else:
            return redirect(reverse('users:login'))
#修改登录密码
class ResetPasswordView(LoginRequiredMixin,View):
    def get(self, request):
        return render(request, 'user_center_pass.html')
    def post(self, request):
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        new_password2 = request.POST.get('new_password2')
        if not  all([old_password, new_password, new_password2]):
           return HttpResponseForbidden('缺少比传数据')
        try:
            if not request.user.check_password(old_password):
                return render(request, 'user_center_pass.html',
                              {'origin_password_errmsg': '原始密码错误'})
        except  Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html',
                          {'origin_password_errmsg': '原始密码错误'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return HttpResponseForbidden('密码最少8位，最长20位')
        if new_password != new_password2:
            return HttpResponseForbidden('两次输入的密码不一致')
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html',
                          {'origin_password_errmsg': '修改密码失败'})
        logout(request)
        response = redirect(reverse('users:login'))
        response.delete_cookie('username')
        return response